/**
 * @author hAmmeRoL, created: 2008-7-9
 * SJTU
 */

package gui;

import java.util.ArrayList;

import protocol.generic.AbstractProtocolManager;
import protocol.domain.GroupEntry;
import protocol.domain.InstantMessage;
import protocol.generic.ProtocolException;

import Delegate.ChatItemDelegate;

import com.trolltech.qt.core.*;
import com.trolltech.qt.gui.*;
import com.trolltech.qt.core.QSize;
import com.trolltech.qt.gui.QCheckBox;
import com.trolltech.qt.gui.QCloseEvent;
import com.trolltech.qt.gui.QIcon;
import com.trolltech.qt.gui.QMainWindow;
import com.trolltech.qt.gui.QPixmap;
import com.trolltech.qt.gui.QStandardItem;
import com.trolltech.qt.gui.QStandardItemModel;
import com.trolltech.qt.gui.QTextDocument;

import com.trolltech.qt.gui.QGraphicsView;

/**
 * Class Representing a chat window between you and your friend
 * 
 * @author hAmmeRoL
 * 
 */
public class ChatWindow extends QMainWindow {

	Ui_ChatWindow ui = new Ui_ChatWindow();
	
	public static QPixmap pixmap001=new QIcon(new QPixmap("classpath:resources/001.png")).pixmap(25, 25);
	public static QPixmap pixmap002=new QIcon(new QPixmap("classpath:resources/002.png")).pixmap(25, 25);
	public static QPixmap pixmap003=new QIcon(new QPixmap("classpath:resources/003.png")).pixmap(25, 25);
	public static QPixmap pixmap004=new QIcon(new QPixmap("classpath:resources/004.png")).pixmap(25, 25);
	public static QPixmap pixmap005=new QIcon(new QPixmap("classpath:resources/005.png")).pixmap(25, 25);
	public static QPixmap pixmap006=new QIcon(new QPixmap("classpath:resources/006.png")).pixmap(25, 25);
	public static QPixmap pixmap009=new QIcon(new QPixmap("classpath:resources/009.png")).pixmap(25, 25);
	
	/**
	 * Signal indicating the window has closed
	 */
	public Signal1<GroupEntry> chatWindowClosed = new Signal1<GroupEntry>();

	// group entry of your buddy
	private GroupEntry entry;

	// the protocol manager
	private AbstractProtocolManager manager;
	
	QStandardItemModel model;
	QComboBox richText;
	QComboBox iconBox;

	/**
	 * Construct a chat window of the GroupEntry entry, the window WILL show
	 * after construction
	 * 
	 * @param entry
	 *            the group entry of this chat window
	 * @param manager
	 *            the manager associated with this window
	 */
	public ChatWindow(MainWindow mw,GroupEntry entry, AbstractProtocolManager manager) {
		super(mw);
		ui.setupUi(this);
		QPixmap pixmap=new QPixmap();
		try {
			pixmap.loadFromData(manager.getAvatar(entry.getID()));
		} catch (Exception e) {
			pixmap=new QPixmap("classpath:resources/receive.png");
		}
		this.setWindowIcon(new QIcon(pixmap));
		if(entry.getAlias()!=null)
			this.setWindowTitle(entry.getAlias());
		else
			this.setWindowTitle(entry.getID());
			
		ChatItemDelegate delegate=new ChatItemDelegate();
		ui.listView.setItemDelegate(delegate);
		ui.listView.setIconSize(new QSize(50, 50));
		ui.listView.setSpacing(3);
		this.entry = entry;
		this.manager = manager;
		this.model=new QStandardItemModel();
		
		ui.sendButton.clicked.connect(this,"sendMessage()");
		ui.sendButton.setShortcut(new QKeySequence("Ctrl+S"));
//		ui.sendButton.clicked.connect(this,"displaySentMessage()");
		ui.sendButton.clicked.connect(ui.textEdit,"clear()");
		ui.closeButton.clicked.connect(this, "close()");
		this.show();
		
		
		ui.action_Bold.triggered.connect(this, "textBold()");
		ui.action_Italic.triggered.connect(this, "textItalic()");
		ui.action_Underline.triggered.connect(this, "textUnderline()");
		
		QComboBox comboFont =new QComboBox(ui.toolBar);
		ui.toolBar.addWidget(comboFont);
		comboFont.setEditable(true);
		QFontDatabase db=new QFontDatabase();
		comboFont.addItems(db.families());
		comboFont.activated.connect(this, "textFamily(String)");
		comboFont.showMinimized();
		comboFont.setCurrentIndex(comboFont.findText(this.font().family(), new Qt.MatchFlags(Qt.MatchFlag.MatchExactly,Qt.MatchFlag.MatchCaseSensitive)));
		
		QComboBox comboSize=new QComboBox(ui.toolBar);
		comboSize.setObjectName("comboSize");
		ui.toolBar.addWidget(comboSize);
		comboSize.setEditable(true);
		for(int i=0;i<QFontDatabase.standardSizes().size();i++){
			int size=QFontDatabase.standardSizes().get(i);
			comboSize.addItem(""+size);
		}
		comboSize.activated.connect(this, "textSize(String)");
		comboSize.setCurrentIndex(comboSize.findText(""+
				this.font().pointSize(),
				new Qt.MatchFlags(Qt.MatchFlag.MatchExactly,Qt.MatchFlag.MatchCaseSensitive)));
		
		iconBox=new QComboBox(ui.toolBar);
		iconBox.addItem(new QIcon(pixmap001), "");
		iconBox.addItem(new QIcon(pixmap002), "");
		iconBox.addItem(new QIcon(pixmap003), "");
		iconBox.addItem(new QIcon(pixmap004), "");
		iconBox.addItem(new QIcon(pixmap005), "");
		iconBox.addItem(new QIcon(pixmap006), "");
		iconBox.addItem(new QIcon(pixmap009), "");
		iconBox.activatedIndex.connect(this, "insertIcon(Integer)");
		ui.toolBar.addWidget(iconBox);
		
		
		richText=new QComboBox(ui.toolBar);
		richText.addItem("Plain");
		richText.addItem("Rich");
		ui.toolBar.addWidget(richText);
		
		//***************************image try*******************************
//		QTextCursor cursor=ui.textEdit.textCursor();
//		QTextImageFormat imageFormat=new QTextImageFormat();
//	    imageFormat.setName("classpath:resources/send.png");
//	    cursor.insertImage(imageFormat);
	}

	/**
	 * Send message using the AbstractProtocolManager associated
	 * 
	 * @param text
	 *            the text message to be sent
	 */
	
	/*
	public void sendMessage(String text) {
		try {
			manager.sendMessage(new InstantMessage(manager.getUserID(), entry
					.getID(), text));
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}*/
	
	public void sendMessage() {
		try {
			QStandardItem item;
			QPixmap pixmap=new QPixmap();
			try {
				pixmap.loadFromData(manager.getAvatar(manager.getUserID()));
			} catch (Exception e) {
				pixmap=new QPixmap("classpath:resources/send.png");
			}
			if(richText.currentIndex()==0){
				manager.sendMessage(new InstantMessage(manager.getUserID(), entry
						.getID(), ui.textEdit.toPlainText()));
				item=new QStandardItem(new QIcon(pixmap),ui.textEdit.toPlainText()+"#Me#"+manager.getUserID());
			}
				
			else{
				manager.sendMessage(new InstantMessage(manager.getUserID(), entry
						.getID(), ui.textEdit.toHtml()));
				QTextDocument doc=new QTextDocument();
		    	doc.setHtml(ui.textEdit.toHtml());
		    	
		    	QTextCursor cursor=new QTextCursor(doc);
		    	cursor.insertText("  Me :\n",new QTextCharFormat());
		    	
		    	
		    	doc.setTextWidth(400);
		    	item=new QStandardItem();
		    	item.setData(new ChatListItem(doc,manager.getUserID(),true,new QIcon(pixmap)),0);
			}
			model.appendRow(item);
			ui.listView.setModel(model);
			ui.listView.scrollToBottom();

		} catch (ProtocolException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Display the message you have sent in the window
	 * 
	 * @param text
	 *            the content of your message. The actual text in the window
	 *            will have your user name and other information in front of the
	 *            message. E.g. You(hAmmeRoL) sent "Hello", and your window will
	 *            display "hAmmeRoL: Hello"
	 */
	
	/*
	public void displaySentMessage(String text) {
		ui.textBrowser.append(manager.getUserID() + ": " + text);
	}
	*/

	/**
	 * Display the message you have received in the window
	 * 
	 * @param text
	 *            the content of the message you received. The actual text in
	 *            the window will have the user name of the received message and
	 *            other information in front of the message. E.g. You have
	 *            received "Hello" from hAmmeRoL, and your window will display
	 *            "hAmmeRoL: Hello"
	 */
	public void displayReceivedMessage(String text) {
		QStandardItem item;
		QPixmap pixmap=new QPixmap();
		try {
			pixmap.loadFromData(manager.getAvatar(entry.getID()));
		} catch (Exception e) {
			pixmap=new QPixmap("classpath:resources/receive.png");
		}
		
		if(text.contains("<!DOCTYPE HTML PUBLIC")){
			QTextDocument doc=new QTextDocument();
	    	doc.setHtml(text);
	    	doc.setTextWidth(440);
	    	
	    	QTextCursor cursor=new QTextCursor(doc);
	    	cursor.insertText("  " + entry.getAlias()+" :\n",new QTextCharFormat());
	    	
	    	item=new QStandardItem();
	    	item.setData(new ChatListItem(doc,manager.getUserID(),true,new QIcon(pixmap)),0);
		}
			
		else{
			item=new QStandardItem(new QIcon(pixmap),text+"#Other#"+entry.getAlias());
		}
		model.appendRow(item);
		ui.listView.setModel(model);
		ui.listView.scrollToBottom();
	}

	/**
	 * Override the close event, make sure the window is disposed
	 */
	public void closeEvent(QCloseEvent event) {
		super.closeEvent(event);
		chatWindowClosed.emit(entry);
	}
	
	public void insertIcon(Integer i){
		String iconPath;
		if(i.intValue()==0)
			iconPath="classpath:resources/001.png";
		else if(i.intValue()==1)
			iconPath="classpath:resources/002.png";
		else if(i.intValue()==2)
			iconPath="classpath:resources/003.png";
		else if(i.intValue()==3)
			iconPath="classpath:resources/004.png";
		else if(i.intValue()==4)
			iconPath="classpath:resources/005.png";
		else if(i.intValue()==5)
			iconPath="classpath:resources/006.png";
		else
			iconPath="classpath:resources/009.png";
		
		QTextCursor cursor=ui.textEdit.textCursor();
		QTextImageFormat imageFormat=new QTextImageFormat();
		imageFormat.setHeight(25);
		imageFormat.setWidth(25);
	    imageFormat.setName(iconPath);
	    cursor.insertImage(imageFormat);
		
	}
	
	
	
	public void textBold(){
		ui.textEdit.setFontWeight(QFont.Weight.Bold.value());
		ui.textEdit.setFontWeight(ui.action_Bold.isChecked()
				?QFont.Weight.Bold.value()
				:QFont.Weight.Normal.value());
	}
	
	public void textItalic(){
		ui.textEdit.setFontItalic(ui.action_Italic.isChecked());
	}
	
	public void textUnderline(){
		ui.textEdit.setFontUnderline(ui.action_Underline.isChecked());
	}
	
	public void textFamily(String f){
		ui.textEdit.setFontFamily(f);
	}
	
	public void textSize(String p){
		ui.textEdit.setFontPointSize(new Float(p));
	}
	
	
	
	
	
	
	
	
	
	
}

